const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/jwt');
const User = require('../models/User');

// 认证中间件
const authenticate = async (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.header('Authorization');
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({ error: '访问被拒绝，缺少访问令牌' });
    }

    // 验证token
    const decoded = jwt.verify(token, jwtConfig.secret);
    const user = await User.findById(decoded.id);
    
    if (!user) {
      return res.status(401).json({ error: '访问被拒绝，用户不存在' });
    }

    req.user = user;
    next();
  } catch (err) {
    res.status(401).json({ error: '访问被拒绝，令牌无效' });
  }
};

module.exports = authenticate;